package org.xml.parser.SAX;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.Book;
import org.xml.sax.SAXException;

public class SAXTest {

	public static void main(String[] args) {
		saxParser();
	}

	public static void saxParser() {
		// 1.获取一个SAXParserFactory的实例
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			// 2.通过factory获取SAXParser实例
			SAXParser parser = factory.newSAXParser();
			// 3.创建一个SAXParserHandler对象
			SAXParserHandler handler = new SAXParserHandler();
			// 4.通过SAXParser对象的parse（String uri,DefaultHandler dh）方法解析xml文件
			parser.parse("books.xml", handler);

			/* 将XML文件中的数据保存在Book对象中并将对象添加到ArrayList中，遍历ArrayList */
			ArrayList<Book> books = handler.getBookList();
			System.out.println("ArrayList中一共保存了" + books.size() + "本书！");
			for (Book book : books) {
				System.out.println(book);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
